package com.blb.controller;

import com.blb.utils.UUIDUtils;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.annotation.MultipartConfig;
import java.io.*;

@MultipartConfig
@Controller
@RequestMapping("resource")
public class UploadController {

    @ResponseBody
    @PostMapping("uploadImg")
    public String uploadImg(MultipartFile file){
        String newName = UUIDUtils.getId();
        try {
            String filename = file.getOriginalFilename();
            String suffix = filename.substring(filename.lastIndexOf("."), filename.length());
            newName = newName + suffix;
            file.transferTo(new File("D:\\IdeaProjects\\blb_erp\\target\\classes\\static\\" + newName));

            uploadImg2(file,newName);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return newName;
    }

    public void uploadImg2(MultipartFile file,String name) throws IOException {

        //创建一个FileOutputStream对象(目标路径)
        FileOutputStream out = new FileOutputStream("D:\\IdeaProjects\\blb_erp\\src\\main\\resources\\static\\" + name);

        //创建一个FileInputStream对象(源文件路径)
        FileInputStream in = new FileInputStream("D:\\IdeaProjects\\blb_erp\\target\\classes\\static\\" + name);
        //进行复制操作
            int len = 0;
            byte[] byts = new byte[1024];
            while ((len = in.read(byts)) != -1) {
                //注意：字节流会直接写入到文件当中，不用刷新缓存
                out.write(byts, 0, len);
            }

            //释放资源
            in.close();
            out.close();

    }
}
